/* eslint-disable react/jsx-no-bind */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/no-did-update-set-state */
/* eslint-disable react/sort-comp */
/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment/moment';
import { debounce, cloneDeep, isEqual } from 'lodash';
import { Card, Form, Select, Button, DatePicker, Spin, Row, Col, Popover, Modal } from 'antd';
import StandardTable from '@/components/StandardTable';
import AddressCascader from '@/components/AddressCascader';
import { Yzs } from '@/components/Select';
import question from '@/assets/question.svg';
import { getLStorage } from '@/utils/utils';
import router from 'umi/router';
import Histogram from './Histogram';
import styles from './style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
const listTypeMapToDownload = {
  inNumDetailList: 'in',
  outRateDetailList: 'out_rate',
  sendOrderDetailList: 'order',
  fansDetailList: 'fans',
};
const downloadNumberType = {
  storageSum: '1',
  smsSum: '9',
  orderSum: '3',
  dakFansSummaryStat: '4',
};

// 明细下载映射
const downloadDetailMap = {
  inNumDetailList: 'in_detail',
  outRateDetailList: 'out_rate_detail',
  sendOrderDetailList: 'order_detail',
  fansDetailList: 'fans_detail',
};

@connect(({ loading, list, area, report, user, setting }) => ({
  list,
  area,
  report,
  searchFormValues: list.searchFormValues,
  address_options: list.address_options,
  userInfo: user.currentUser.user_info,
  exportLoading: loading.effects['report/getExportTask'],
  ...setting,
}))
@Form.create()
export default class StatisticalData extends Component {
  state = {
    reqYzPayload: {},
    isZyAccount: false,
    codeArr: [], // 驿站传参需要的code
    isFansPage: false, //  是否是粉丝页面
    listTypeInState: 'inNumDetailList',
    visible: false,
    hasSearched: false,
    currentLevel: 0,
  };

  handleSearchForthe = debounce(
    e => {
      e && e.preventDefault();
      this.getList(1, 10);
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  componentDidMount() {
    const { listType, userInfo = {}, options = {} } = this.props;
    const { branch = [] } = userInfo;
    const { key } = options;

    this.setState({
      isZyAccount: key === 'post',
      codeArr: branch.map(i => i.code),
      isFansPage: listType === 'dakFansSummaryStat',
    });
  }

  componentDidUpdate(prevProps, prevState) {
    const { isZyAccount, codeArr } = this.state;
    const { codeArr: oldCodeArr } = prevState;
    const {
      searchFormValues,
      listType,
      userInfo: { branch = [] },
      areaRankKey,
      area_id,
      options: { key },
    } = this.props;
    const {
      searchFormValues: _searchFormValues,
      listType: _listType,
      areaRankKey: oldAreaRnakKey,
      area_id: oldZoneId,
    } = prevProps;
    const reqZoneId = key === 'yz' ? area_id : null;
    const addressId = searchFormValues[`${listType}AddressId`] || [];
    const oldAddressId = _searchFormValues[`${_listType}AddressId`] || [];
    let code = []; // 驿站下拉首次请求需要的code
    const branchId = [...addressId].pop(); // 中邮选择驿站所需要的id
    // 根据所选区域设置对应驿站列表
    if (!isEqual(oldCodeArr, codeArr) && !isZyAccount) {
      this.setState({
        reqYzPayload: {
          code: [...codeArr].pop(),
          area_id: reqZoneId,
        },
      });
    }
    if (!isEqual(addressId, oldAddressId)) {
      if (codeArr.length == 0) {
        code = branch.map(i => i.code).pop();
      } else {
        code = [...codeArr].pop();
      }
      this.setState({
        reqYzPayload: {
          [isZyAccount ? 'branch_id' : 'code']: isZyAccount ? branchId : code,
          area_id: reqZoneId,
        },
      });
    }
    if (areaRankKey !== oldAreaRnakKey) {
      // 监听从总览跳转过来的情况
      areaRankKey && this.onTypeClick(areaRankKey);
    }
    if (area_id !== oldZoneId) {
      this.setState(prev => ({
        reqYzPayload: {
          ...prev.reqYzPayload,
          area_id: reqZoneId,
        },
      }));
      this.handleSearchForthe();
    }
  }

  onTypeClick = debounce(
    listType => {
      const { dispatch } = this.props;
      dispatch({
        type: 'list/save',
        payload: {
          listType,
        },
      });
      this.setState({
        listTypeInState: listType,
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  getFormValues = (then, isExport = false, page = 1) => {
    const {
      form,
      listType,
      dispatch,
      userInfo,
      areaRankingListType,
      searchFormValues,
    } = this.props;
    const { branch = [], branchLevel } = userInfo;
    const formType = areaRankingListType || listType; // 兼容区域排名的表单数据
    const defaultBrandId = searchFormValues[`${formType}BrandId`];
    let init_branch;
    if (branchLevel == 0 && branch.length == 0) {
      init_branch = [
        {
          id: '0',
          name: '中国邮政集团有限公司',
          level: '0',
          pid: '-2', // 自定义pid用来区分是否是单独属于总公司账号
        },
      ];
    } else {
      init_branch = branch;
    }

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = cloneDeep(fieldsValue);
      const { date } = values;

      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start = start;
        values.end = end;
        delete values.date;
      }
      // 缓存搜索数据，防止数据导出再次请求接口
      !isExport &&
        dispatch({
          type: 'list/setFormValues',
          payload: {
            [`${formType}Date`]: fieldsValue.date,
            [`${formType}SiteId`]: fieldsValue.cm_id,
            [`${formType}AddressId`]: fieldsValue.address || [],
            [`${formType}BrandId`]: fieldsValue.brand || defaultBrandId,
            page,
            listType,
            areaRankingListType,
            init_branch,
          },
        });
      then({
        ...values,
      });
    });
  };

  handleStandardTableChange = pagination => {
    const { current, pageSize } = pagination;
    this.getList(current, pageSize);
  };

  getList = (page, pageSize) => {
    const { isZyAccount, codeArr = [], isFansPage } = this.state;
    const {
      dispatch,
      listType,
      chart,
      statisticalType,
      areaRankingListType,
      options: { key },
      userInfo,
    } = this.props;
    const { phone, inn_area_ids = [], area_ids } = userInfo;
    const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
    const isCompany = area_ids == '*';
    // 防止片区被关闭，导致请求带上上一个的片区ID
    const area_id = inn_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : inn_area_ids.join(',');
    const reqZoneId = key === 'yz' ? area_id : null;
    this.getFormValues(
      fieldsValue => {
        const values = {
          ...fieldsValue,
        };
        const { cm_id, brand, start, end, address = [] } = values;
        const payload = {
          cm_id,
          brand,
          start,
          end,
          code: isZyAccount ? [...address].pop() : [...codeArr].pop(),
          page,
          page_num: pageSize,
          area_id: reqZoneId,
        };
        if (!payload.brand) {
          payload.brand = 'all';
        }
        if (!payload.cm_id) {
          payload.cm_id = 'all';
        }
        if (statisticalType == 'brand') {
          // 兼容区域选择时选择粉丝数查询
          if (isFansPage) {
            if (isZyAccount) {
              delete payload.cm_id;
            }
            delete payload.code;
          }
          delete payload.brand;
        }
        if (areaRankingListType) return; // 防止在区域选择页面点击查询，重复掉接口
        chart &&
          dispatch({
            type: `list/${chart}`,
          });
        dispatch({
          type: `list/${listType}`,
          payload,
        });
        this.setState({
          hasSearched: true,
        });
      },
      false,
      page,
    );
  };

  dataClick = data => {
    const { form } = this.props;
    const setFieldsValueDate = {
      startDate: moment()
        .startOf('day')
        .subtract(data, 'days'),
      endDate: moment()
        .endOf('day')
        .subtract(1, 'days'),
    };
    form.setFieldsValue({
      date: [setFieldsValueDate.startDate, setFieldsValueDate.endDate],
    });
  };

  // 品牌下拉
  onGetOperatorList = visible => {
    if (!visible) return;
    const { dispatch } = this.props;
    const { currentStation, operator } = this.state;
    const { list } = operator || {};
    const { code } = currentStation || { code: '0' };
    if (list) return;
    const shop_id = code == '0' ? '' : code;
    dispatch({
      type: 'list/getBrandsList',
      payload: {
        shop_id,
      },
      then: () => {},
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
    return false;
  };

  downloadData = type => {
    const { isZyAccount, codeArr, isFansPage } = this.state;
    const {
      form: { getFieldsValue },
    } = this.props;
    const { cm_id, brand, date, address = [] } = getFieldsValue();
    const inn_ids = cm_id ? (cm_id == 'all' ? 0 : cm_id) : 0;
    const brands = brand || 'all';
    const code = isZyAccount ? [...address].pop() : [...codeArr].pop();
    const data = {
      type: downloadNumberType[type],
      cm_id: inn_ids,
      brand: brands,
      start_date: moment(date[0]).format(dateFormat),
      end_date: moment(date[1]).format(dateFormat),
      code,
    };
    if (isFansPage) {
      if (isZyAccount) {
        delete data.cm_id;
      }
      delete data.code;
    }
    return { ...data };
  };

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i += 1) {
      result.push(i);
    }
    return result;
  };

  disabledDate = current =>
    // Can not select days before today and today
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(1, 'days');

  disabledRangeTime = (_, type) => {
    if (type === 'end') {
      return {
        disabledHours: () => this.range(0, 60).splice(4, 20),
        disabledMinutes: () => this.range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    }
    return {
      disabledHours: () => this.range(0, 60).splice(20, 4),
      disabledMinutes: () => this.range(0, 31),
      disabledSeconds: () => [55, 56],
    };
  };

  onAddressSelect = (value, selectedOptions) => {
    const {
      dispatch,
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({
      cm_id: 'all',
    });
    const codeArr = selectedOptions.map(val => {
      for (let i = 0; i < value.length; i += 1) {
        const id = value[i];
        if (id == val.id) {
          return val.code || '';
        }
      }
    });
    const currentLevel = selectedOptions[selectedOptions.length - 1].level;
    this.setState({
      codeArr,
      currentLevel,
    });
    dispatch({
      type: 'list/save',
      payload: {
        address_options: [selectedOptions[0]],
      },
    });
  };

  // 根据所选区域设置对应驿站列表
  onPopupVisibleChange = visible => {
    const { isZyAccount } = this.state;
    const {
      form: { getFieldsValue },
    } = this.props;
    if (!visible) {
      const { address } = getFieldsValue(['address']);
      isZyAccount &&
        this.setState({
          reqYzPayload: {
            branch_id: [...address].pop(),
          },
        });
    }
  };

  onAreaExportClick = type => {
    const { dispatch, listType } = this.props;
    const { isZyAccount, codeArr = [] } = this.state;
    this.getFormValues(values => {
      const { brand, start, end, address = [] } = values;
      const payload = {
        brand,
        start_date: start,
        end_date: end,
        code: isZyAccount ? [...address].pop() : [...codeArr].pop(),
        type: type == 'detail' ? downloadDetailMap[listType] : listTypeMapToDownload[listType],
      };
      dispatch({
        type: 'report/getAreaExportTask',
        payload,
      }).then(() => {
        this.setState({
          visible: true,
        });
      });
    }, true);
  };

  handleOk = () => {
    this.setState(
      {
        visible: false,
      },
      () => {
        router.push('/downloadReport');
      },
    );
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  onExportClick = type => {
    const { dispatch } = this.props;
    const payload = this.downloadData(type);

    dispatch({
      type: 'report/asyncExport',
      payload,
    });
  };

  render() {
    const {
      formItemLayout,
      form,
      operatoring,
      dropList,
      loading,
      data,
      columns,
      statisticalType,
      listType,
      searchFormValues,
      address_options,
      userInfo,
      chartTitle,
      histogramList = [],
      activeKey,
      rankType,
      areaRankingListType, // 兼容区域排名搜索框的数据缓存
      exportLoading,
    } = this.props;
    const formType = areaRankingListType || listType;
    const {
      reqYzPayload,
      isFansPage,
      isZyAccount,
      listTypeInState,
      visible,
      hasSearched,
      currentLevel,
    } = this.state;
    const { getFieldDecorator } = form;
    const defaultSelectDate = {
      startDate: searchFormValues[`${formType}Date`] && searchFormValues[`${formType}Date`][0],
      endDate: searchFormValues[`${formType}Date`] && searchFormValues[`${formType}Date`][1],
    };
    const defaultSiteId = searchFormValues[`${formType}SiteId`];
    const defaultAddressId = searchFormValues[`${formType}AddressId`] || [];
    const defaultBrandId = searchFormValues[`${formType}BrandId`];
    const branch = searchFormValues.init_branch || [];
    const defaultAddressOPtions = address_options || [];
    // 支局和粉丝页面需要屏蔽驿站下拉
    const showYZS =
      (!isFansPage || (isZyAccount && userInfo.branchLevel == '4')) && activeKey !== 'areaRanking';
    return (
      <div>
        <Form onSubmit={this.handleSearchForthe} className={styles['search-form']} layout="inline">
          <FormItem>
            <a className={styles.select_date} onClick={() => this.dataClick(1)}>
              昨日
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(7)}>
              近7日
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(30)}>
              近30日
            </a>
          </FormItem>
          <FormItem {...formItemLayout} className={styles.data}>
            {getFieldDecorator('date', {
              initialValue: [defaultSelectDate.startDate, defaultSelectDate.endDate],
            })(
              <RangePicker
                style={{ width: '280px' }}
                placeholder={['开始日期', '结束日期']}
                disabledDate={this.disabledDate}
                disabledTime={this.disabledRangeTime}
              />,
            )}
          </FormItem>
          {showYZS && (
            <FormItem {...formItemLayout} className={styles.data}>
              {getFieldDecorator('cm_id', {
                initialValue: defaultSiteId,
              })(<Yzs style={{ width: '150px' }} reqPayload={reqYzPayload} />)}
            </FormItem>
          )}
          {!isFansPage && (
            <FormItem>
              {getFieldDecorator('address', {
                initialValue: defaultAddressId,
              })(
                <AddressCascader
                  canChooseParent={!isZyAccount}
                  path="modify"
                  level={3}
                  placeholder="请选择区域"
                  width={300}
                  request
                  branch={branch}
                  changeOnSelect
                  onSelect={this.onAddressSelect}
                  optionsFromProps={defaultAddressOPtions}
                  onPopupVisibleChange={this.onPopupVisibleChange}
                />,
              )}
            </FormItem>
          )}
          {statisticalType !== 'brand' && (
            <FormItem {...formItemLayout} className={styles.data}>
              {getFieldDecorator('brand', {
                initialValue: defaultBrandId,
              })(
                <Select
                  onDropdownVisibleChange={this.onGetOperatorList}
                  filterOption={this.onFilterOperator}
                  showSearch
                  allowClear
                  placeholder="全部品牌"
                  style={{ width: '150px' }}
                >
                  {operatoring ? (
                    <Option disabled value="loading">
                      <Spin />
                    </Option>
                  ) : (
                    <Option key="all" value="all">
                      全部品牌
                    </Option>
                  )}
                  {dropList &&
                    dropList.map(({ brand_en, brand }) => (
                      <Option key={brand_en} value={brand_en}>
                        {brand}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
          )}
          <FormItem>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" key="search" loading={loading} icon="search">
                查询
              </Button>
            </span>
            {activeKey !== 'areaRanking' && (
              <div
                style={{
                  marginLeft: '16px',
                  display: 'inline-block',
                }}
              >
                <Button
                  type="primary"
                  icon="download"
                  onClick={() => this.onExportClick(listType)}
                  loading={exportLoading}
                  disabled={isZyAccount && (!hasSearched || data?.list?.length == 0)}
                >
                  导出
                </Button>
              </div>
            )}
          </FormItem>
          <FormItem>
            <Popover
              trigger="click"
              title="汇总规则"
              content={
                <div>
                  <p>选择全国总司时，按省汇总</p>
                  <p>选择省公司时，按市汇总</p>
                  <p>选择市公司时，按县汇总</p>
                  <p>选择县公司时，按驿站汇总</p>
                </div>
              }
            >
              <img
                alt=""
                onClick={this.onQuestionClick}
                style={{ cursor: 'pointer', marginLeft: 5 }}
                src={question}
              />
            </Popover>
          </FormItem>
          {activeKey == 'areaRanking' && (
            <Row type="flex" style={{ marginTop: 10, height: 30 }} align="middle">
              <Col style={{ width: 70 }}>
                <div className={styles.type} onClick={() => this.onTypeClick('inNumDetailList')}>
                  <span className={listTypeInState == 'inNumDetailList' ? styles.checked : ''}>
                    入库数
                  </span>
                </div>
              </Col>
              <Col style={{ width: 70 }}>
                <div className={styles.type} onClick={() => this.onTypeClick('outRateDetailList')}>
                  <span className={listTypeInState == 'outRateDetailList' ? styles.checked : ''}>
                    出库率
                  </span>
                </div>
              </Col>
              <Col style={{ width: 80 }}>
                <div
                  className={styles.type}
                  onClick={() => this.onTypeClick('sendOrderDetailList')}
                >
                  <span className={listTypeInState == 'sendOrderDetailList' ? styles.checked : ''}>
                    寄件订单
                  </span>
                </div>
              </Col>
              <Col style={{ width: 80 }}>
                <div className={styles.type} onClick={() => this.onTypeClick('fansDetailList')}>
                  <span className={listTypeInState == 'fansDetailList' ? styles.checked : ''}>
                    公众号粉丝
                  </span>
                </div>
              </Col>
            </Row>
          )}
        </Form>
        {activeKey == 'areaRanking' && (
          <>
            <Card>
              <Histogram title={chartTitle} list={histogramList} rankType={rankType} />
            </Card>
            <Row type="flex" style={{ width: '100%' }} justify="space-between">
              <Col>
                <h2>明细数据</h2>
              </Col>
              <Col>
                <Row type="flex" gutter={[20, 0]}>
                  <Col>
                    <Button
                      type="primary"
                      icon="download"
                      onClick={this.onAreaExportClick.bind(this, 'total')}
                      loading={exportLoading}
                    >
                      导出汇总
                    </Button>
                  </Col>
                  {currentLevel == 2 && (
                    <Col>
                      <Button
                        type="primary"
                        icon="download"
                        onClick={this.onAreaExportClick.bind(this, 'detail')}
                        loading={exportLoading}
                      >
                        导出明细
                      </Button>
                    </Col>
                  )}
                </Row>
              </Col>
            </Row>
          </>
        )}
        <StandardTable
          rowKey={record => record.id || record.city_id || record.dak_id}
          loading={loading}
          data={data}
          columns={columns}
          onChange={this.handleStandardTableChange}
        />
        <Modal
          title="报表生成中"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="立即前往"
          cancelText="稍后前往"
        >
          您可前往“报表下载“中下载
        </Modal>
      </div>
    );
  }
}
